<template>
    <div ref="weather" class="weather_wrapper">
        <div id="he-plugin-standard"></div>
    </div>
</template>
<script>
import axios from 'axios'
export default {
    name: "WeatherInfo",
    data() {
        return {
            loading: false,
            mapKey: '0a6447eb39596684e4bcdf8b949e797a',
            today: {},
            week: {}
        }
    },
    mounted() {
        this.showWeatherInfo();
        // window.onresize = () => {
        //     this.showWeatherInfo();
        // }
    },
    destroyed() {
        window.onresize = null;
    },
    methods: {
        showWeatherInfo() {
            let width = parseInt(window.getComputedStyle(this.$refs.weather).width);
            window.WIDGET = {
                "CONFIG": {
                    "layout": '1',
                    // "layout": width >= 280 ? "1" : '2',
                    "width": 300,
                    "height": 150,
                    // "height": width >= 280 ? 200 : 280,
                    "background": "1",
                    "dataColor": "FFFFFF",
                    "borderRadius": "5",
                    "key": "19eba4e63f2e43b3a2c74c8f0c6f7855"
                }
            }
            let script = document.createElement('script')
            script.type = 'text/javascript'
            script.src = 'https://widget.qweather.net/standard/static/js/he-standard-common.js?v=2.0'
            document.getElementsByTagName('head')[0].appendChild(script)
        },
        //根据ip获取城市编码
        async getCityCode() {
            this.loading = true;
            try {
                let res = await axios.get(`https://restapi.amap.com/v3/ip?key=${this.mapKey}`);
                let { adcode } = res.data;
                await this.getWeatherInfo(adcode, 'base', 'today')
                await this.getWeatherInfo(adcode, 'all', 'week')
            } finally {
                this.loading = false;
            }
        },
        //获取天气信息
        async getWeatherInfo(adcode, extensions, type) {
            try {
                //天气
                let res = await axios.get(`https://restapi.amap.com/v3/weather/weatherInfo?city=${adcode}&extensions=${extensions}&key=${this.mapKey}`);
                console.log(res)
                if (type == 'today') {
                    this.today = res.data.lives[0];
                } else {
                    this.week = res.data.forecasts[0];
                }
            } finally {
            }
        }
    }
}
</script>